#include<iostream>
#include<cstring>
#include<string>
#include<sys/socket.h>
#include<sys/types.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<unistd.h>

using namespace std;

void Usage(const string& proc)
{
    cout<<"\nUsage:"<<proc<<"serverip serverport\n"<<endl;
}
//./tcpclient serverip serverport
int main(int argc,char* argv[])
{
    if(argc!=3)
    {
        Usage(argv[0]);
        exit(1);
    }

    string serverip=argv[1];
    uint16_t serverport=stoi(argv[2]);

    int sockfd=socket(AF_INET,SOCK_STREAM,0);
    if(sockfd<0)
    {
        cout<<"socket create error,error:"<<errno<<"strerror:"<<strerror(errno)<<endl;
        return 1;
    }

    struct sockaddr_in server;
    memset(&server,0,sizeof(server));
    server.sin_family=AF_INET;
    server.sin_port=htons(serverport);
    inet_pton(AF_INET,serverip.c_str(),&(server.sin_addr));


    int n=connect(sockfd,(struct sockaddr*)&server,sizeof(server));
    if(n<0)
    {
        cerr<<"connect error..."<<endl;
        return 2;
    }
    cout<<"connect successfully..."<<endl;

    string messege;
    while(true)
    {
        cout<<"Please Enter#"<<endl;
        getline(cin,messege);

        write(sockfd,messege.c_str(),messege.size());

        char buffer[4096];

        int n=read(sockfd,buffer,sizeof(buffer));
        if(n>0)
        {
            cout<<"服务器的回应："<<buffer<<endl;
        }
        else if(n==0)
        {
            cout<<"server close fd, so i close my sockfd..."<<endl;
            close(sockfd);
            break;
        }
    }

    return 0;
}